//
//  YCLHomeViewController.swift
//  新浪微博01
//
//  Created by yaochunlin on 16/4/8.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
//上拉加载更多
import SVPullToRefresh

class YCLHomeViewController: YCLBaseTableViewController {
    
    //微博数据数组
    var statues:[YCLStatus]?{
    
        didSet{
        
            YCLPrint("总的微博数据:\(statues?.count)")
            self.tableView.reloadData()
        }
    }
    
    private let reuseIdentifier = "reuseIdentifier"
    

    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        //判断用户是否登录
        if !YCLUserAccountViewModel.sharedUserAccountViewModel.isLogin{
            
            YCLPrint("请先登录")
            return
        }
        
        //注册cell
        tableView.registerClass(YCLStatusCell.self, forCellReuseIdentifier: reuseIdentifier)
        
        //设置cell行高自适应
        tableView.rowHeight = UITableViewAutomaticDimension
        
        //设置预估行高
        tableView.estimatedRowHeight = 200
        
        //取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        prepareUI()
        
//        //获取微博数据
//        YCLStatusViewModel.sharedStatusViewModel.loadStatusData { (statuses, error) in
//            
//            if error != nil {
//            
//                YCLPrint("获取微博数据失败")
//                return
//            }
//            
//            self.statues = statuses
//            self.tableView.reloadData()
//            
////            YCLPrint("微博模型:\(self.statues)")
//        }
    }
    
    private func prepareUI() {
        
        //下拉刷新
        tableView.addSubview(pullDownRefreshControl)
        
        pullDownRefreshControl.pullDownRefreshHandler = {
            
//            //模拟耗时操作
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { 
//                
//                YCLPrint("结束刷新")
//                
//                self.pullDownRefreshControl.endRefreshing()
//            })
            self.loadNewStatus()
            
        }
        
        //自动开始刷新
        self.pullDownRefreshControl.startRefreshing()
 
        
        
        //添加左右两边导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem.creatUIBarButtonItem("navigationbar_friendsearch")
        navigationItem.rightBarButtonItem = UIBarButtonItem.creatUIBarButtonItem("navigationbar_pop")
        
        //添加中间标题
        let name = YCLUserAccountViewModel.sharedUserAccountViewModel.userAccount?.screen_name ?? "没有名字"
        
        navigationItem.titleView = YCLHomeTitleBtn.init(title: name)
    
    }
    
    //加载更多旧的微博数据
    private func loadMoreOldStatus() {
    
        let max_id = statues?.last?.id ?? 0
        
        if max_id == 0 {
            
            YCLPrint("没有更多数据")
            return
        }
        
        YCLStatusViewModel.sharedStatusViewModel.loadStatusData(0, max_id: max_id) { (statuses, error) in
            
            //停止上拉刷新控件动画
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
            
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
                return
            }
            
            //加载更多数据成功
            self.statues = self.statues! + statuses!
            
            
        }
        
        
    }
    
    //加载新的微博数据
    private func loadNewStatus() {
    
        //获取id最大的微博，若果没有就默认加载20条数据
        let since_id = statues?.first?.id ?? 0
        
        YCLStatusViewModel.sharedStatusViewModel.loadStatusData(since_id, max_id: 0) { (statuses, error) in
            
            //让刷新控件完成刷新
            self.pullDownRefreshControl.endRefreshing()
            
            if error != nil {
            
                YCLPrint("下载数据失败\(error)")
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
                return
            }
            
            //判断返回微博的数量
            let count = statuses?.count ?? 0
//            YCLPrint("count:\(count)")
            
            if since_id != 0 {
            
                self.showPullDownTip(count)
            }
            
            if count == 0 {
            
                SVProgressHUD.showErrorWithStatus("没有新的数据")
                return
            }
            
            if since_id == 0 {
            
                self.statues = statuses
                
                //MARK 上拉加载更多微博信息
                self.tableView.addInfiniteScrollingWithActionHandler {
                    
                    self.loadMoreOldStatus()
                }
                
            }else{
            
                self.statues = statuses! + self.statues!
            }
  
        }
    }
    
    //下拉刷新提示框
    private func showPullDownTip(count: Int) {
        
        tipLabel.text = count == 0 ? "没有微博数据" : "加载了\(count)条微博数据"
        //实现动画
        UIView.animateWithDuration(1, animations: {
            
            self.tipLabel.frame.origin.y = labelHeight
            }) { (_) in
                
                UIView.animateWithDuration(1, delay: 0.2, options: UIViewAnimationOptions(rawValue:0), animations: {
                    
                    self.tipLabel.frame.origin.y = -(UIApplication.sharedApplication().statusBarFrame.height + labelHeight)
                    }, completion: { (_) in
                        
                })
        }
        
        
    }
    
    
    @objc private func friendsearchBtnClick(){
    
        YCLPrint("点击了查找朋友按钮")
    }
    
    @objc private func popBtnClick(){
    
        YCLPrint("点击了扫一扫按钮")
    }
    
    //MARK 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statues?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! YCLStatusCell
        
        cell.status = statues![indexPath.row]

        return cell
        
    }
    
    //MARK 懒加载下拉刷新控件
    private lazy var pullDownRefreshControl: YCLPullDownRefreshControl = YCLPullDownRefreshControl()
    
    //懒加载下拉刷新提示框
    private lazy var tipLabel:UILabel = {
        
        let label = UILabel.init(frame: CGRect.init(x: 0, y: -(UIApplication.sharedApplication().statusBarFrame.height + labelHeight), width: UIScreen.mainScreen().bounds.width, height: labelHeight))
        
        label.font = UIFont.systemFontOfSize(16)
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        label.backgroundColor = UIColor.orangeColor()
        
        //加到navBar上（最底端）
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
        
    }()


}

